import Message from '@/components/antds/Message';
import type { AxiosRequestConfig } from 'axios';
import axios from 'axios';
import instance, { showMsg } from './instance';

export type IRequestMethod = 'get' | 'post';

export const http = {
  request(config: AxiosRequestConfig) {
    return instance
      .request(config)
      .then(
        (response) => {
          if (response.data.status !== 0) {
            const msg = showMsg(response);

            if (msg) {
              Message.error(msg);
            }
          }



          return response
            ? Promise.resolve(response.data)
            : Promise.reject(new Error('no response'));
        },
        (error) => {
          return Promise.reject(error);
        },
      )
      .catch((error) => {
        if (axios.isCancel(error)) {
          console.log('Request canceled', error.message);
        }

        return Promise.reject(error);
      });
  },
  get(url: string, params?: GObject, config?: AxiosRequestConfig) {
    return this.request({ ...config, url, method: 'get', params });
  },
  post(url: string, data?: GObject, config?: AxiosRequestConfig) {
    return this.request({ ...config, url, method: 'post', data });
  },
};
